import chalk from 'chalk';
import fs from 'fs';

const log = console.log;

export default function extractNpmRely() {
  fs.readFile('./.umirc.ts', 'utf8', (err, data) => {
    if (err) throw err;
    const regexConfig =
      /export\s+default\s+defineConfig\(\s*{([\s\S]+?)}\s*\);/;
    let match = data.match(regexConfig)[1];
    const endsWithComma = match.trim().endsWith(',');
    if (!endsWithComma) {
      match = match + ',';
    }

    const str = `externals: {
            react: "React",
            "react-dom": "ReactDOM",
            dayjs: "dayjs",
            lodash:"lodash"
          },
            headScripts: [
            "https://unpkg.com/react@18.2.0/umd/react.production.min.js",
            "https://unpkg.com/react-dom@18.2.0/umd/react-dom.production.min.js",
            "https://unpkg.com/dayjs/dayjs.min.js",
            "https://unpkg.com/lodash@4.17.21/lodash.js"
          ],`;

    const additionalContent = `\n ${str}\n`;

    const modifyData = data.replace(
      regexConfig,
      `export default defineConfig({ ${match + additionalContent} })`,
    );

    fs.writeFile('./.umirc.ts', modifyData, function (err) {
      if (err) throw err;
      log(chalk.green('配置更新成功'));
    });
  });
}
